#include <stdio.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdlib.h>

int main()
{
    int fd1[2], fd2[2];
    pipe(fd1);
    pipe(fd2);

    pid_t pid1 = fork();
    if(pid1 < 0)
    {
        perror("pid1 failed");
        exit(1);
    }
    else if(pid1 == 0)
    {
        close(fd1[0]);
        dup2(fd1[1], STDOUT_FILENO);
        close(fd1[1]);
        close(fd2[0]);
        close(fd2[1]);
        execlp("ls", "ls", NULL);
        perror("ls failed");
        exit(1);
    }

    pid_t pid2 = fork();
    if(pid2 < 0)
    {
        perror("pid2 failed");
        exit(1);
    }
    else if(pid2 == 0)
    {
        close(fd1[1]);
        close(fd2[0]);
        dup2(fd1[0], STDIN_FILENO);
        dup2(fd2[1], STDOUT_FILENO);
        close(fd1[0]);
        close(fd2[1]);
        execlp("grep", "grep", ".c", NULL);
        perror("grep failed");
        exit(1);
    }

    close(fd2[1]);
    dup2(fd2[0], STDIN_FILENO);
    close(fd1[0]);
    close(fd1[1]);

    int fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    dup2(fd, STDOUT_FILENO);
    close(fd);

    execlp("wc", "wc", "-l", NULL);
    perror("wc failed");
    exit(1);

    wait(NULL);
    wait(NULL);

    return 0;
}
